package tech.dubbo.trigger.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/10/5
 */
public class MapEncoder extends MessageToByteEncoder<Map<String, Object>> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Map<String, Object> msg, ByteBuf byteBuf) throws Exception {
        // 使用 ObjectOutputStream 将 Map 序列化为字节数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(msg);
        objectOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();

        // 写入长度
        byteBuf.writeInt(bytes.length);
        // 写入内容
        byteBuf.writeBytes(bytes);
    }
}
